/**
 * 
 */
package net.sahv.bdyz.controller.web;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;

import net.sahv.bdyz.model.Address;
import net.sahv.bdyz.model.Fabric;
import net.sahv.bdyz.model.FabricFilter;
import net.sahv.bdyz.model.HelpCenter;
import net.sahv.bdyz.model.Member;
import net.sahv.bdyz.model.MemberAttention;
import net.sahv.bdyz.model.Pattern;
import net.sahv.bdyz.model.PatternPrint;
import net.sahv.bdyz.service.FabricFilterService;
import net.sahv.bdyz.service.FabricService;
import net.sahv.bdyz.service.HelpCenterService;
import net.sahv.bdyz.service.LanguageService;
import net.sahv.bdyz.service.MemberAttentionService;
import net.sahv.bdyz.service.MemberService;
import net.sahv.bdyz.service.PatternPrintService;
import net.sahv.bdyz.service.PatternService;
import net.sahv.bdyz.util.FileUpLoadNew;
import net.sahv.bdyz.util.FixedImgCompress;
import net.sahv.bdyz.util.LoadCfgUtil;
import net.sahv.bdyz.util.WaterMark;
import net.sahv.bdyz.util.testImg;

/**
 * @author 张天敏
 * @date 日期：2016年8月4日 时间：下午6:45:13
 */
@Controller
@RequestMapping("web/pattern")
public class PatternController {
	
	@Autowired
	private PatternService patternService;//花型列表
	@Autowired
	private FabricFilterService fabricFilterService;//花型列表
	@Autowired
	private FabricService fabricService;
	@Autowired
	private PatternPrintService patternPrintService;     //数码印花工艺表
	@Autowired 
	CookieLocaleResolver resolver;
	@Autowired
	private LanguageService languageService;// 语言
	@Autowired
	private HelpCenterService helpCenterService;
	@Autowired
	private MemberService memberService;// 会员
	@Autowired
	private MemberAttentionService memberAttentionService;// 会员关注信息
	
	/**
	 * 跳转到花型目录
	 * @author 张天敏
	 * @date 日期：2016年8月4日 时间：下午6:47:15
	 * @return
	 */
	@RequestMapping(value="/flowerTypeCatalog",method=RequestMethod.GET)
	public String flowerTypeCatalog(){		
		return "redirect:/web/patternfilter/all/flowertypecatalog1";
	}
	
	/**
	 * 跳转到试衣界面
	 * @author 张天敏
	 * @date 日期：2016年8月10日 时间：下午6:15:22
	 * @return
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	@RequestMapping(value="/flowerCatalog",method=RequestMethod.GET)
	public String flowerCatalog(Model model,Integer id,HttpServletRequest request,HttpServletResponse response) throws FileNotFoundException, IOException{
		String language = languageService.getCurrentLanguage();
		
		Map<String, String> mapUrls = LoadCfgUtil.loadCfg();
		
		List<Fabric> fabricListFIngredientsList=new ArrayList<Fabric>();
		Member member = memberService.getCurrent();//获取当前登录人信息
		if (member == null) {
			return "web/member/login";
		}
		MemberAttention memberattention = new MemberAttention();
		memberattention.setAtttype(4);
		memberattention.setAttid(id);
		memberattention.setCreatetime(new Date());
		memberattention.setIsdelete(0);
		memberattention.setMid(member.getmId());
		memberAttentionService.insert(memberattention);
		
		//查询花型
		Pattern pattern =  patternService.selectByPrimaryKey(id);
		//生成水印图片
		makeWaterMark(mapUrls,request,pattern);
		
		List<Pattern> patternlist =  patternService.findAllBylimit(pattern);
		//查询成分
		List<FabricFilter> fabricFilterList=fabricFilterService.selectByFfParentId(1);
		for(FabricFilter fabricFilter:fabricFilterList){
			//查询成分面料
			List<Fabric> fabricList=fabricService.selectByFIngredients(fabricFilter.getFfId());
			for(Fabric fabric:fabricList){
				//将成分信息国际化
				if (language != null && language.equals("en")) {
					fabric.setfName(fabric.getfMessage1());
				}
				
				fabricListFIngredientsList.add(fabric);
			}
		}
		
		//查询面料成分对应的数码印花工艺
		List<Map<String,Object>>  patternPrintMapList=patternPrintService.selectPatternPrintByFfid(fabricFilterList.get(0).getFfId());
		List<PatternPrint> patternPrintList=mapChangeToEntity(patternPrintMapList);
		//查询全部的数码印花工艺
		List<PatternPrint> patternPrintAll=patternPrintService.selectAllPrint();
		
		HelpCenter helpCenter=helpCenterService.selectDetails(8);//买断花型
		model.addAttribute("helpCenter", helpCenter);
		if (language != null && language.equals("en")) {			
			helpCenter.sethContent(helpCenter.gethContentEn());//买断花型
			for (FabricFilter ff : fabricFilterList) {
				ff.setFfName(ff.getFfNameEn());
			}
			for (PatternPrint pp : patternPrintList) {
				pp.setPpName(pp.getPpNameEn());
			}
			//将数码印花工艺面板国际化
			for(PatternPrint patternPrint:patternPrintAll){
				patternPrint.setPpName(patternPrint.getPpNameEn());
			}
		}
		
		model.addAttribute("imgpath",mapUrls.get("targetUrl.img"));		
		model.addAttribute("pattern", pattern);
		model.addAttribute("patternlist", patternlist);
		model.addAttribute("fabricFilterList", fabricFilterList);
		model.addAttribute("fabricListFIngredientsList", fabricListFIngredientsList);
		model.addAttribute("patternPrintList", patternPrintList);
		model.addAttribute("patternPrintAll", patternPrintAll);
		return "web/pattern/flowerCatalog";
	}
	
	/**
	 * @author 张天敏
	 * @date 日期：2016年10月7日 时间：上午8:58:51
	 * @param patternPrint
	 * @param patternPrintMapList
	 */
	public static List<PatternPrint> mapChangeToEntity(List<Map<String, Object>> patternPrintMapList) {
			//将Map型的数组转换成实体类数组
			List<PatternPrint> patternPrintList=new ArrayList<PatternPrint>();
			for(Map<String,Object> patternPrintMap:patternPrintMapList){
				Integer PP_ID=(Integer) patternPrintMap.get("PP_ID");
				String PP_NAME=(String) patternPrintMap.get("PP_NAME");
				String PP_NAME_EN=(String) patternPrintMap.get("PP_NAME_EN");
				BigDecimal PP_PRICE=(BigDecimal) patternPrintMap.get("PP_PRICE");
				PatternPrint patternPrint=new PatternPrint();
				patternPrint.setPpId(PP_ID);
				patternPrint.setPpName(PP_NAME);
				patternPrint.setPpNameEn(PP_NAME_EN);
				patternPrint.setPpPrice(PP_PRICE);
				patternPrintList.add(patternPrint);
			}
			return patternPrintList;
	}

	/**
	 * 制作水印图片
	 * @author 张天敏
	 * @param mapUrls 
	 * @param request 
	 * @param pattern 
	 * @throws IOException 
	 * @date 日期：2016年9月20日 时间：上午10:57:22
	 */
	private void makeWaterMark(Map<String, String> mapUrls, HttpServletRequest request, Pattern pattern) throws IOException {

		//输入图片路径：
		String imgUrl=mapUrls.get("targetUrl.img")+pattern.getpImg();
		
		//输出图片的路径
		String compression=mapUrls.get("local.uploadImgPath.compression");
		//由于花型源图片存放在别的服务器上，所以说不会在本地被压缩成缩略图，故将生成水印之前的压缩图放在此路径下不会出现重复
		String outputPath=request.getServletContext().getRealPath(compression+pattern.getpImg());
		//生成固定尺寸图片
		FixedImgCompress.initCompression(imgUrl, outputPath);
		//对图片进行添加水印:iconPath(充当水印的图片路径), srcImgPath（背景图片路径）, targerIconPath（输出的合成图片路径）
		String iconPath=request.getServletContext().getRealPath("/upload/waterMark/"+"aa.png");
		//合成图片路径
		String targerIconPath=request.getServletContext().getRealPath("/upload/waterMark/"+pattern.getpImg());
		//设置水印的打印位置
		WaterMark.setImageMarkOptions(0.7f, 1, 1, null, null);
		//生成水印图片
		WaterMark.markImageByIcon(iconPath, outputPath, targerIconPath);
		
	}

	/**
	 * tab面板
	 * @author 张天敏
	 * @date 日期：2016年8月12日 时间：上午10:18:32
	 * @return
	 */
	@RequestMapping(value="/flowerCatalogUp",method=RequestMethod.GET)
	public String flowerCatalogUp(Model model){
		HelpCenter helpCenter=helpCenterService.selectDetails(8);//买断花型
		String language = languageService.getCurrentLanguage();
		if (language.equals("en")) {
			helpCenter.sethContent(helpCenter.gethContentEn());//买断花型
		}
		model.addAttribute("helpCenter", helpCenter);
		return "web/pattern/flowerCatalogUp";
	}
	
	/**
	 * 花型面板
	 * @author 张天敏
	 * @date 日期：2016年8月12日 时间：上午10:19:19
	 * @return
	 */
	@RequestMapping(value="/flowerCatalogDown",method=RequestMethod.GET)
	public String flowerCatalogDown(){
		return "web/pattern/flowerCatalogDown";
	}
			
	/**
	 * 发布试衣指令
	 * 王聪朝 
	 * 2016年8月15日10:31:04
	 * @return
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping(value="/writeTxt")
	public void writeTxt(String isrc) throws IOException
	{				
		FileOutputStream fos = new FileOutputStream("C:\\wamp\\www\\test.txt",true);//true表示在文件末尾追加
		fos.write(("\r\n"+isrc).getBytes());
		fos.close();//流要及时关闭		
	}

	/**
	 * 
	 * @author 作者 : 任凯伟
	 * @date 创建时间：2016年8月22日 上午9:48:21
	 * @version 1.0
	 * @see 进入试衣间
	 * @param
	 * @parameter
	 * @since
	 * @return
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	@RequestMapping(value = "/goFittingRoom", method = RequestMethod.GET)
	public String goFittingRoom(Model model, HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException {
		Map<String, String> mapUrls = LoadCfgUtil.loadCfg();
		String imgParent = mapUrls.get("targetUrl.img");
		//从session中获取当前时间
		String language = languageService.getCurrentLanguage();
		List<Fabric> fabricListFIngredientsList = new ArrayList<Fabric>();
		List<Pattern> patternlist = patternService.findDefaultPattern();
		// 查询面料
		List<FabricFilter> fabricFilterList = fabricFilterService.selectByFfParentId(1);
		for (FabricFilter fabricFilter : fabricFilterList) {
			List<Fabric> fabricList = fabricService.selectByFIngredients(fabricFilter.getFfId());
			for (Fabric fabric : fabricList) {
				if (language != null && language.equals("en")) {
					fabric.setfName(fabric.getfMessage1());
				}
				fabricListFIngredientsList.add(fabric);
			}
			//面料帅选条件，如果是系统设定的语言是英语，则将英文字段覆盖中文字段来显示英文
			if (language != null && language.equals("en")) {
				fabricFilter.setFfName(fabricFilter.getFfNameEn());
			}
		}
		// 数码印花工艺
		List<PatternPrint> patternPrintList = patternPrintService.selectAllPrint();
		for(PatternPrint patternPrint:patternPrintList){
			if (language != null && language.equals("en")) {
				patternPrint.setPpName(patternPrint.getPpNameEn());
			}
		}
		model.addAttribute("imgpath", imgParent);
		model.addAttribute("patternlist", patternlist);
		model.addAttribute("fabricFilterList", fabricFilterList);
		model.addAttribute("fabricListFIngredientsList", fabricListFIngredientsList);
		model.addAttribute("patternPrintList", patternPrintList);
		return "web/pattern/flowerCatalog";
	}
	

	/**
	 * 图片添加水印
	 * 王聪朝 2016年8月23日15:03:21
	 * @param request
	 * @param ImgPath
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/testImg")
	public  int  testImg(HttpServletRequest request,String ImgPath){
		String realPath = request.getServletContext().getRealPath(ImgPath);		
		File file=new File(realPath);    
		if(!file.exists())    
		{    
		  return 0;
		}    
	    testImg ib = new testImg();
	    ib.ImgYin("布调一致", realPath);
	    return 1;
	}
	
	@ResponseBody
	@RequestMapping(value="/testImgKuaYu",method=RequestMethod.GET)
	public  String  testImgKuaYu(HttpServletRequest request,String ImgPath,String s,String n) throws FileNotFoundException, IOException{
		
		Map<String,String> mapUrls=LoadCfgUtil.loadCfg();
		String testImgBD=mapUrls.get("targetUrl.testImgBD");
		
        Map<String, String> textMap = new HashMap<String, String>();  

        textMap.put("ImgPath", ImgPath);    
        textMap.put("s", s);    
        textMap.put("n", n);  
        //textMap.put("fileName", fileName);

        Map<String, InputStream> fileMap = new HashMap<String, InputStream>();  

        //fileMap.put("imgNeedEnglish",  (FileInputStream)fileInputStream);  
        
        String ret = FileUpLoadNew.formUpload(testImgBD, textMap, fileMap,"");  

        return ret;
	}
		
	
	@ResponseBody
	@RequestMapping(value="/writeTxtKuaYu",method=RequestMethod.POST)
	public String writeTxtKuaYu(HttpServletRequest request,String isrc) throws IOException
	{		
		
			Map<String,String> mapUrls=LoadCfgUtil.loadCfg();
			String writeTxt=mapUrls.get("targetUrl.writeTxt");
	        
	        Map<String, String> textMap = new HashMap<String, String>();  

	        textMap.put("isrc", isrc);          

	        Map<String, InputStream> fileMap = new HashMap<String, InputStream>();  
	        
	        String ret = FileUpLoadNew.formUpload(writeTxt, textMap, fileMap,"");  

	        return ret;
	    
	}
	
	/**
	 * 根据面料成分查找相应的数码印花工艺信息
	 * @author 张天敏
	 * @date 日期：2016年10月7日 时间：上午8:47:08
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/requestPatternPrint",method=RequestMethod.POST)
	public ApiResult requestPatternPrint(Integer id){
		//查询当前语言
		String language = languageService.getCurrentLanguage();
		ApiResult result=new ApiResult();
		List<Map<String,Object>> patternPrintMapList=patternPrintService.selectPatternPrintByFfid(id);
		List<PatternPrint> patternPrintList=mapChangeToEntity(patternPrintMapList);
		if (language != null && language.equals("en")) {
			for(PatternPrint patternPrint:patternPrintList){
				//如果当前语言为英文，则用英文字段覆盖中文字段
				patternPrint.setPpName(patternPrint.getPpNameEn());
			}
			
		}
		
		if(patternPrintList!=null&&patternPrintList.size()>0){
			result.msg.status=0;
			result.msg.desc="查询成功！";
			result.data.put("patternPrintList", patternPrintList);
		}else{
			result.msg.status=1;
			result.msg.desc="查询结果不存在！";
		}
		return result;
	}
	
}
